// 封装路由相关的内容
// 1、引入路由
import VueRouter from "vue-router"
import Vue from "vue"
// 2、注册
Vue.use(VueRouter)
// 3、路由规则
let routes = [
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: "/login",
        // component: ()=>import("../views/login.vue")
        // @ 表示src这个目录的别名
        component: ()=>import("@/views/login.vue")
    },
    {
        path: "/register",
        component: ()=>import("@/views/register.vue")
    },
    {
        path: "/personal",
        component: ()=>import("@/views/personal.vue")
    },
    {
        path: "/edit_profile",
        component: ()=>import("@/views/edit_profile.vue")
    },
    {
        path: "/index",
        component: ()=>import("@/views/index.vue")
    },
    {
        path: "/articleDetail",
        component: ()=>import("@/views/articleDetail.vue")
    },
    {
        path: "/commentList",
        component: ()=>import("@/views/commentList.vue")
    },{
        path: "/category",
        component: ()=>import("@/views/category.vue")
    },
    {
        path: "/search",
        component: ()=>import("@/views/search.vue")
    }
]
// 4、生成路由对象
let router = new VueRouter({
    routes
})
import { Toast } from "vant"
// 全局前置守卫：路由跳转页面之前会触发的一个函数
// 需求：个人中心页面，必须要登录后才能访问
// 需要登录后才能访问的页面，都添加到此数组中，这个数组我就叫白名单数组
const writeArr = ["/personal", "/edit_profile", "/category"]; 
router.beforeEach((to, from, next)=>{
    let token = localStorage.getItem("74-token")
    // 表示用户跳转到个人中心页面且没登录
    if( writeArr.indexOf(to.path) !=-1 &&!token ){
        Toast.fail("请登录！")
        // 跳转到登录页面
        // location.href = "http://localhost:8080/#/login"
        next("/login") // 表示跳转进入指定路由路径中
    }else{
        next()
    }
})


// 解决重复跳转同一个路由报错问题
// 重新下载路由也能解决这个问题 ---- 这些代码不用记，直接百度一下就出来了
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// 5、导出路由对象
export default router